#include "FbUtils.h"

#include <EIKENV.H>
#include <EIKAPPUI.H>
#include <eikapp.h>

#include <CHARCONV.H>
#include <s32file.h>
#include "constdefined.hrh"

//获取程序AppUi对象句柄
CFlashbox4AppUi *GetAppUi ()
{
	return (CFlashbox4AppUi *) CEikonEnv::Static ()->EikAppUi ();
}

// 读取unicode文本
HBufC * ReadUnicodeFileL (RFs& aFs, const TDesC& aFileName )
{
	RFile file;
	User::LeaveIfError (file.Open (aFs, aFileName, EFileShareReadersOnly
			| EFileStreamText | EFileRead ) );
	CleanupClosePushL (file );

	TInt size;
	User::LeaveIfError (file.Size (size ) );

	RBuf8 tmp;
	tmp.CreateL (size );
	CleanupClosePushL (tmp );
	User::LeaveIfError (file.Read (tmp ) );

	CCnvCharacterSetConverter * converter = CCnvCharacterSetConverter::NewLC ();
	converter->PrepareToConvertToOrFromL (KCharacterSetIdentifierUtf8, aFs );

	HBufC *text = HBufC::NewL (size );
	
	TInt state = CCnvCharacterSetConverter::KStateDefault;
	TPtrC8 remainderOfForeignText (tmp );
	for (;; )
	{
		TPtr textPtr (text->Des () );
		TInt retValue = converter->ConvertToUnicode (textPtr,
				remainderOfForeignText, state );
		if (retValue == CCnvCharacterSetConverter::EErrorIllFormedInput )
			User::Leave (KErrCorrupt );
		else
			if (retValue < 0 )
				User::Leave (KErrGeneral );

		if (retValue == 0 )
			break;
		
		remainderOfForeignText.Set (remainderOfForeignText.Right (retValue ) );
	}

	CleanupStack::PopAndDestroy (converter );
	CleanupStack::PopAndDestroy (2 );
	return text;
}

/**
 * 生成手机客户端系统信息节点
 */
CXmlNode * GetMobileInfoNode ()
{
	CXmlNode *pNode = CXmlNode::NewL (KClientInfoType );
	CleanupStack::PushL (pNode );
	pNode->AddNodeL (KModel, GetAppUi()->m_mobileInfo.iModel);//model
	pNode->AddNodeL (KImei, GetAppUi()->m_mobileInfo.iSerialNumber );
	pNode->AddNodeL (KVersion, KAppVersion);
	CleanupStack::Pop ();
	return pNode;
}

/**
 * 字符转为数字
 */
TInt String2Int(const TDesC8 &aStr)
{
	TInt rtn = 0;
	TLex8 lex(aStr);
	lex.Val(rtn);
	
	return rtn;
}

/*
 * 给文件路径添加指定盘符
 */
TFileName  AddDrive(TFileName &aFile)
{
	TParse parse;
	parse.Set(CEikonEnv::Static()->EikAppUi()->Application()->AppFullName(), NULL, NULL);
	//parse.Drive();
	HBufC* tmpBuf = HBufC::NewL(100);
	aFile.Insert(0, parse.Drive());
	
	return aFile;
}
